import javax.swing.JOptionPane;
import java.sql.*;

public class DBUtil {
    private static final String URL = "jdbc:mysql://localhost:3306/bus_ticket_system?serverTimezone=UTC&useSSL=false";
    private static final String USER = "root";  // 数据库用户名
    private static final String PASSWORD = "@Aaysc666";  // 数据库密码

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("MySQL驱动加载成功,正在记录购票记录");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库驱动加载失败", "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL, USER, PASSWORD);
    }

    public static void saveTicketRecord(TicketRecord record) {
        String sql = "INSERT INTO ticket_records (payment_method, is_success, amount, start_station, end_station) " +
                     "VALUES (?, ?, ?, ?, ?)";
        
        try (Connection conn = getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            
            pstmt.setString(1, record.getPaymentMethod());
            pstmt.setBoolean(2, record.isSuccess());
            pstmt.setDouble(3, record.getAmount());
            pstmt.setString(4, record.getStartStation());
            pstmt.setString(5, record.getEndStation());
            
            pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(null, "数据库操作失败: " + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
}